package com.parktech.sun.web.controller;

import com.parktech.sun.domain.model.downloadcenter.ResourceFile;
import com.parktech.sun.domain.service.downloadcenter.ResourceFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * User: Think
 * Date: 11-1-16
 * Time: 下午4:09
 */
@Controller
public class DownloadsController {

    @Autowired
    private ResourceFileService resourceFileService;

    @RequestMapping("/downloads/{domain}/{domainId}/{fileName}.{extendName}")
    public void download(@PathVariable("domain") String domain,
                         @PathVariable("domainId") String domainId,
                         @PathVariable("fileName") String fileName,
                         @PathVariable("extendName") String extendName,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException, FileNotFoundException {

        if (domain.equals("resourceFile")) {
            ResourceFile resourceFile = resourceFileService.getById(new Long(domainId));
            resourceFile.setDownloadCount(resourceFile.getDownloadCount() + 1);
            resourceFileService.saveOrUpdateBean(resourceFile);
        }
        String fullFilePath = request.getSession().getServletContext().getRealPath("/upload");
        fullFilePath += "/" + domain + "/" + domainId + "/" + fileName + "." + extendName;
        File file = new File(fullFilePath);
        /*如果文件存在*/
        if (file.exists()) {
            String filename = URLEncoder.encode(file.getName(), "UTF-8");
            response.reset();
            response.setContentType("pplication/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            int fileLength = (int) file.length();
            response.setContentLength(fileLength);
            /*如果文件长度大于0*/
            if (fileLength != 0) {
                /*创建输入流*/
                InputStream inStream = new FileInputStream(file);
                byte[] buf = new byte[4096];
                /*创建输出流*/
                ServletOutputStream servletOS = response.getOutputStream();
                int readLength;
                while (((readLength = inStream.read(buf)) != -1)) {
                    servletOS.write(buf, 0, readLength);
                }
                inStream.close();
                servletOS.flush();
                servletOS.close();
            }
        }
    }
}
